use core::ptr::null_mut;

use crate::{
    c::{
        osEventFlagsAttr_t, osEventFlagsClear, osEventFlagsId_t, osEventFlagsNew, osEventFlagsSet, osEventFlagsWait, osFlagsWaitAll, osFlagsWaitAny, osRtxEventFlags_t
    },
    error::{parse, Error},
    utils::Align8Store,
};

const CB_SIZE: usize = size_of::<osRtxEventFlags_t>();

pub struct EventFlags {
    cb_mem: Align8Store<CB_SIZE>,
    id: osEventFlagsId_t,
}

impl EventFlags {
    pub const fn default() -> Self {
        Self {
            cb_mem: Align8Store::new(),
            id: null_mut(),
        }
    }

    pub fn new(&mut self, name: &str) {
        let attr = osEventFlagsAttr_t {
            name: name.as_ptr() as *const i8,
            attr_bits: 0,
            cb_mem: self.cb_mem.raw_ptr(),
            cb_size: CB_SIZE as u32,
        };
        self.id = unsafe { osEventFlagsNew(&attr) };
        assert!(self.id != null_mut(), "event falgs new fail");
    }

    pub fn set_flags(&self, flags: u32) -> Result<u32, Error> {
        let r = unsafe { osEventFlagsSet(self.id, flags) };
        parse(r)
    }

    pub fn clr_flags(&self, flags: u32) -> Result<u32, Error> {
        let r = unsafe { osEventFlagsClear(self.id, flags) };
        parse(r)
    }

    pub fn wait_any_flags(&self, flags: u32, timeout: u32) -> Result<u32, Error> {
        let r = unsafe { osEventFlagsWait(self.id, flags, osFlagsWaitAny, timeout) };
        parse(r)
    }

    pub fn wait_all_flags(&self, flags: u32, timeout: u32) -> Result<u32, Error> {
        let r = unsafe { osEventFlagsWait(self.id, flags, osFlagsWaitAll, timeout) };
        parse(r)
    }
}
